#include "dlg_bookgs.h"
#include "ui_dlg_bookgs.h"

Dlg_BookGS::Dlg_BookGS(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dlg_BookGS)
{
    ui->setupUi(this);

    //设置tableView无法编辑
    ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    //设置tableView只能选择单行
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);

    ui->tableView->setModel(&m_model);
}

Dlg_BookGS::~Dlg_BookGS()
{
    delete ui;
}

void Dlg_BookGS::setBookid(int bookid)
{
    this->bookid = bookid;
}

void Dlg_BookGS::initBookView()
{
    QMap<QString, QString> bookMap = SqlMgr::getInstance()->findBook(this->bookid);
    ui->le_bookid->setText(QString::number(this->bookid));
    ui->le_bookname->setText(bookMap.value("name"));
    ui->le_cnt->setText(bookMap.value("cnt"));
    ui->le_price->setText(bookMap.value("price"));
}

void Dlg_BookGS::initUserView()
{
    this->m_model.clear();

    QString strCondition = QString("where 1=1 ");

    if("" != ui->le_search_username->text()){
        strCondition.append(" and username like '%" + ui->le_search_username->text() + "%'");
    }

    qDebug() << strCondition;

    QVector<QStringList> userList = SqlMgr::getInstance()->getUsers(strCondition);

    this->m_model.setHorizontalHeaderLabels({"用户ID", "姓名", "密码", "昵称", "权限", "部门", "班级"});

    int rows = userList.size();
    for(int i = 0; i < rows; i++){
        QList<QStandardItem *> items;
        int cols = userList[i].size();
        for(int j = 0; j < cols; j++){
            items.append(new QStandardItem(userList[i][j]));
        }
        m_model.appendRow(items);
    }

}

void Dlg_BookGS::on_btn_search_clicked()
{
    this->initUserView();
}

void Dlg_BookGS::on_btn_borrow_clicked()
{
    QModelIndex modelIndex = ui->tableView->currentIndex();
    int currentRowIndex = modelIndex.row();

    qDebug() << "当前选中的行号:" << currentRowIndex;

    if(currentRowIndex < 0){
        QMessageBox::warning(this, "提示", "请选中一行记录");
        return;
    }

    QStandardItem * item = this->m_model.item(currentRowIndex, 0);
    QString userid = item->text();

    qDebug() << "userid=" << userid;

    bool flag = SqlMgr::getInstance()->borrowBook(userid, QString::number(this->bookid));

    if(flag){
        QMessageBox::information(this, "提示", "借阅成功!");
        return;
    }

    QMessageBox::critical(this, "错误", "借阅失败!");

}
